import BaseComponent from '@/components/BaseComponent';
import SourceData from '@/components/SourceData';
import tool from '@/utils/tool';
import _ from 'lodash';

export default class SourceDataView extends BaseComponent {
  constructor(props) {
    super(props);
    this.sourceData = new SourceData({
      context: this,
      convert(res) {
        if (_.isArray(res)) {
          return res;
        }
        return _.get(res, 'data.data') || _.get(res, 'data');
      },
    });
  }

  didMount() {
    this.sourceData.initSource().finally(() => {
      this.setState({});
    });
  }

  render() {
    const {
      children,
      value,
      textKey = 'text',
      valueKey = 'value',
    } = this.props;
    let source = this.sourceData.getSource() || [];
    if (typeof children === 'function') {
      return children(tool.getSourceValue(value, source, { valueKey }));
    }
    let info = tool.getSourceValue(value, source, { valueKey }) || {};
    return info[textKey] || null;
  }
}
